//
//  AddGuestViewController.m
//  QRMaster
//
//  Created by lc on 16/5/30.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "AddGuestViewController.h"
#import "AddMemberCell.h"
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "AreaChooseController.h"
#import "validateInputValue.h"
#import "GuestManagerViewController.h"
#import "GuestLogic.h"
#import "GroupGuestLogic.h"
@interface AddGuestViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,ABPeoplePickerNavigationControllerDelegate,UIAlertViewDelegate>

@property (nonatomic,strong) UITableView * memberTableView;
@property (nonatomic,strong) UIImageView * promtView;//提示操作页面
@property (nonatomic,strong) UIImageView * editImgView;
@property (nonatomic,strong) UIButton * finishBtn;
@property (nonatomic,strong) UITextField * phoneTextField;
@property (nonatomic,strong) UITextField * emailTextField;
@property (nonatomic,strong) UITextField * nameTextField;
@property (nonatomic,strong) UITextField * ceritificateTextField;
@property (nonatomic,strong) UIButton * areaBtn;
@property (nonatomic,strong) UIButton * linkmanBtn;
@property (nonatomic,strong) UIView * line;
@property (nonatomic,strong) NSUserDefaults * userInfo;
@property (nonatomic,strong) NSMutableDictionary * saveDict;
@property (nonatomic,assign) BOOL phoneFlag; //默认按手机，yes为选中，no为没选中
@property (nonatomic,assign) BOOL manFlag;    //默认性别选男，yes为选中，no为没选中
@property (nonatomic,copy) NSString * type;  //判断为手机还是邮箱，手机为1，邮箱为0
@property (nonatomic,copy) NSString * sex;   //判断当前性别，男为1，女为0

@end

@implementation AddGuestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title  = NSLocalizedString(@"addGuest", nil);
    _userInfo = [NSUserDefaults standardUserDefaults];
    _saveDict = [[NSMutableDictionary alloc]init];
    
    _phoneFlag = YES;
    _manFlag = YES;
    _type = @"1";
    _sex = @"1";
//    if ([[_userInfo objectForKey:@"address"]isEqualToString:@"yes"]) {
//        [self preparePromtView];
//    }
    
    [self prepareNaviBar];
    [self prepareTableView];
}

//#pragma mark -- 操作提示页面
//-(void)preparePromtView
//{
//    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
//    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
//    float x = 0;
//    float y = 0;
//    float width = ScreenWidth;
//    float height = ScreenHeight;
//    
//    _promtView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
//    _promtView.backgroundColor = RGBA(0, 0, 0, 0.5);
//    _promtView.userInteractionEnabled = YES;
//    [self.view addSubview:_promtView];
//    UITapGestureRecognizer * promtViewClick = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickPromtView)];
//    [_promtView addGestureRecognizer:promtViewClick];
//    
//    x = 0;
//    width = ScreenWidth;
//    height = 380.0 / 640 * width;
//    y = 64;
//    UIImageView * addressImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
//    addressImgView.image = [UIImage imageNamed:NSLocalizedString(@"addStaffPromt", nil)];
//    [_promtView addSubview:addressImgView];
//    
//}
//
//-(void)clickPromtView
//{
//    [_promtView removeFromSuperview];
//    [_userInfo setValue:@"no" forKey:@"address"];
//    [_userInfo synchronize];
//}

- (void)prepareNaviBar{
    _finishBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
    _finishBtn.backgroundColor = [UIColor clearColor];
    _finishBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [_finishBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [_finishBtn setTitle:NSLocalizedString(@"takePost", nil) forState:UIControlStateNormal];
    [_finishBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:UIControlStateNormal];
    [_finishBtn setTitleColor:UIColorFromRGBAndA(0x7dc234, 0.5) forState:UIControlStateDisabled];
    [_finishBtn addTarget:self action:@selector(finishClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * finishItem = [[UIBarButtonItem alloc] initWithCustomView:_finishBtn];
    finishItem.enabled = NO;
    self.navigationItem.rightBarButtonItem = finishItem;
}

- (void)prepareTableView{
    
    //地区选择button
    _areaBtn = [[UIButton alloc] initWithFrame:CGRectMake(22, 0, 50, 44)];
    _areaBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _areaBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_areaBtn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [_areaBtn setTitle:@"+86" forState:UIControlStateNormal];
    [_areaBtn addTarget:self action:@selector(chooseArea) forControlEvents:UIControlEventTouchUpInside];
    
    //分割线
    _line = [[UIView alloc] initWithFrame:CGRectMake(72, 0, 0.5, 44)];
    _line.backgroundColor = UIColorFromRGB(0xc1c1c1);
    
    //手机输入框
    _phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(88, 0, UI_SCREEN_WIDTH-88-45, 44)];
    _phoneTextField.textColor = UIColorFromRGB(0x333333);
    _phoneTextField.font = [UIFont systemFontOfSize:15];
    _phoneTextField.tag = 101;
    _phoneTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"inputMobile", nil) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:UIColorFromRGB(0x727272)}];
    [_phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    //联系人
    _linkmanBtn = [[UIButton alloc] initWithFrame:CGRectMake(UI_SCREEN_WIDTH-40, 10, 24, 24)];
    [_linkmanBtn setBackgroundImage:[UIImage imageNamed:@"ic-txl-green"] forState:UIControlStateNormal];
    [_linkmanBtn addTarget:self action:@selector(chooseLinkman) forControlEvents:UIControlEventTouchUpInside];
    
    //邮箱输入框
    _emailTextField = [[UITextField alloc] initWithFrame:CGRectMake(22, 0, UI_SCREEN_WIDTH-22, 44)];
    _emailTextField.textColor = UIColorFromRGB(0x333333);
    _emailTextField.font = [UIFont systemFontOfSize:15];
    _emailTextField.tag = 102;
    _emailTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入邮箱" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:UIColorFromRGB(0x727272)}];
    [_emailTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    //姓名输入框
    _nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(22, 0, UI_SCREEN_WIDTH-22, 44)];
    _nameTextField.textColor = UIColorFromRGB(0x333333);
    _nameTextField.font = [UIFont systemFontOfSize:15];
    _nameTextField.tag = 103;
    _nameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"inputName", nil) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:UIColorFromRGB(0x727272)}];
    [_nameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    //身份证
    _ceritificateTextField = [[UITextField alloc] initWithFrame:CGRectMake(22, 0, UI_SCREEN_WIDTH-22, 44)];
    _ceritificateTextField.textColor = UIColorFromRGB(0x333333);
    _ceritificateTextField.font = [UIFont systemFontOfSize:15];
    _ceritificateTextField.tag = 104;
    _ceritificateTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入身份证" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:UIColorFromRGB(0x727272)}];
    [_ceritificateTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    //整个tableView
    _memberTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _memberTableView.backgroundColor = UIColorFromRGB(0xebebeb);
    _memberTableView.separatorInset = UIEdgeInsetsMake(0, 22, 0, 0);
    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 5)];
    _memberTableView.tableHeaderView = headerView;
    _memberTableView.dataSource = self;
    _memberTableView.delegate = self;
    [self.view addSubview:_memberTableView];
    
}

#pragma mark - 输入框监听
- (void)textFieldDidChange:(UITextField *)textField{
    
//    if ( (_phoneTextField.text.length!=0 && _nameTextField.text.length!=0 && _ceritificateTextField.text.length!=0) || (_emailTextField.text.length!=0 && _nameTextField.text.length!=0 && _ceritificateTextField.text.length!=0)) {
//        self.navigationItem.rightBarButtonItem.enabled = YES;
//    }else{
//        self.navigationItem.rightBarButtonItem.enabled = NO;
//    }
    if ( (_phoneTextField.text.length!=0 && _nameTextField.text.length!=0) || (_emailTextField.text.length!=0 && _nameTextField.text.length!=0)) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else{
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }


    
}

#pragma mark - 完成点击事件
- (void)finishClick{
    [self resignClick];
    NSString * localizString = NSLocalizedString(@"sureAdd", nil);
    NSString * alertString = [[NSString alloc] init];
    if([_type intValue]==1)
    {
        if (![validateInputValue isPureNumandCharacters:_phoneTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil)];
            return;
        }
        alertString = [NSString stringWithFormat:@"%@%@？",localizString, _phoneTextField.text];
    }else{
        if (![validateInputValue validateEmail:_emailTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil)];
            return;
        }
        alertString = [NSString stringWithFormat:@"%@%@？",localizString, _emailTextField.text];
    }
    
    if ([validateInputValue validateStringIsNull:_nameTextField.text]) {
        [PromptInfoView showMessage:NSLocalizedString(@"userNameLength", nil) superView:self.view];
        return;
    }
    
    
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:alertString delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil) otherButtonTitles:NSLocalizedString(@"alterSure", nil), nil];
    [alert show];
}

-(void)resignClick
{
    [_nameTextField resignFirstResponder];
    [_phoneTextField resignFirstResponder];
    [_emailTextField resignFirstResponder];
    [_ceritificateTextField resignFirstResponder];
}


#pragma mark - 选择地区
- (void)chooseArea{
    AreaChooseController * acc = [[AreaChooseController alloc]init];
    [self.navigationController pushViewController:acc animated:YES];
    acc.areaCode = ^(NSString * areaCodeString,NSString * areaString)
    {
        [_areaBtn setTitle:[NSString stringWithFormat:@"+%@",areaCodeString] forState:UIControlStateNormal];
    };
}

#pragma mark - 从通讯录添加成员
- (void)chooseLinkman{
    ABPeoplePickerNavigationController * peoplePicker = [[ABPeoplePickerNavigationController alloc]init];
    peoplePicker.peoplePickerDelegate = self;
    [self presentViewController:peoplePicker animated:NO completion:nil];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==1 || section==2 ||section==3){
        return 1;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_phoneFlag) {     //手机
        _type = @"1";
    }else{     //邮箱
        _type = @"0";
    }
    
    if (_manFlag) {   //男
        _sex = @"1";
    }else{      //女
        _sex = @"0";
    }
    
    NSString * ID = @"memberCell";
    if (indexPath.section==0 || indexPath.section==4) {
        AddMemberCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell==nil) {
            cell = [[AddMemberCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        switch (indexPath.section) {
            case 0:
                if (indexPath.row==0) {
                    cell.rowLabel.text = NSLocalizedString(@"editTelePhone", nil);
                    cell.isClick = _phoneFlag;
                }else{
                    cell.rowLabel.text = NSLocalizedString(@"mineEmail", nil);
                    cell.isClick = !_phoneFlag;
                }
                break;
            case 4:
                if (indexPath.row==0) {
                    cell.rowLabel.text = NSLocalizedString(@"man", nil);
                    cell.isClick = _manFlag;
                }else{
                    cell.rowLabel.text = NSLocalizedString(@"woman", nil);
                    cell.isClick = !_manFlag;
                }
                break;
            default:
                break;
        }
        return cell;
    }else{
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell==nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            cell.backgroundColor = [UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.section==2){
            [cell.contentView addSubview:_nameTextField];
        }else if (indexPath.section==3){
            [cell.contentView addSubview:_ceritificateTextField];
        }else{
            
            for (UIView * view in [cell.contentView subviews]) {
                [view removeFromSuperview];
            }
            if ([_type intValue]==1) {
                [cell.contentView addSubview:_areaBtn];
                [cell.contentView addSubview:_line];
                [cell.contentView addSubview:_phoneTextField];
                [cell.contentView addSubview:_linkmanBtn];
            }else{
                [cell.contentView addSubview:_emailTextField];
            }
        }
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            _phoneFlag = !_phoneFlag;
            break;
        case 4:
            _manFlag = !_manFlag;
            break;
        default:
            break;
    }
    [_memberTableView reloadData];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 34;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 34)];
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(16, 9, 60, 16)];
    switch (section) {
        case 0:
            label.text = NSLocalizedString(@"type", nil);;
            break;
        case 1:
            if ([_type intValue]==1) {
                label.text = NSLocalizedString(@"editTelePhone", nil);
            }else{
                label.text = NSLocalizedString(@"mineEmail", nil);
            }
            break;
        case 2:
            label.text = NSLocalizedString(@"userName", nil);
            break;
        case 3:
            label.text = NSLocalizedString(@"certificate", nil);
            break;
        case 4:
            label.text = NSLocalizedString(@"sex", nil);
            break;
        default:
            break;
    }
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = UIColorFromRGB(0x333333);
    [contentView addSubview:label];
    return contentView;
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
{
    ABMutableMultiValueRef phoneMult = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString * fisrtName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString * lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (fisrtName == nil) {
        fisrtName = @"";
    }
    if (lastName == nil) {
        lastName = @"";
    }
    _nameTextField.text = [NSString stringWithFormat:@"%@%@",lastName,fisrtName];
    
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMult); i ++) {
        NSString * aphone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMult, i);
        [phones addObject:aphone];
    }
    if (phones.count > 0) {
        _phoneTextField.text = [phones objectAtIndex:0];
        _phoneTextField.text = [_phoneTextField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
//    if (_ceritificateTextField.text.length!=0) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
//    }else{
//        self.navigationItem.rightBarButtonItem.enabled = NO;
//    }
    
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

//2_0到8_0系统使用的方法
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    ABMutableMultiValueRef phoneMult = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString * fisrtName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString * lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (fisrtName == nil) {
        fisrtName = @"";
    }
    if (lastName == nil) {
        lastName = @"";
    }
    _nameTextField.text = [NSString stringWithFormat:@"%@%@",lastName,fisrtName];
    
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMult); i ++) {
        NSString * aphone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMult, i);
        [phones addObject:aphone];
    }
    if (phones.count > 0) {
        _phoneTextField.text = [phones objectAtIndex:0];
        _phoneTextField.text = [_phoneTextField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    return NO;
}

#pragma mark -- alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self makeSureSave];
    }
}

- (void)makeSureSave{
    [self.view endEditing:YES];
    if ([self IsHaveNetwork]) {
        return;
    }
    NSString * postString = nil;
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    _saveDict = [[NSMutableDictionary alloc]init];
    if (_groupId) {
        [_saveDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
        [_saveDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
        [_saveDict setValue:_communityId forKey:@"communityId"];
        [_saveDict setValue:_groupId forKey:@"groupId"];
        if ([_type intValue]==1) {
            if([validateInputValue isPureNumandCharacters:_phoneTextField.text]==YES)
            {
                [_saveDict setValue:_phoneTextField.text forKey:@"mobile"];
                [_saveDict setValue:[_areaBtn.titleLabel.text substringFromIndex:1] forKey:@"areaCode"];
            }
        }else{
            if ([validateInputValue validateEmail:_emailTextField.text]==YES)
            {
                [_saveDict setValue:_emailTextField.text forKey:@"email"];
            }
        }
//        if([validateInputValue isPureNumandCharacters:_phoneTextField.text]==YES)
//        {
//            [_saveDict setValue:_phoneTextField.text forKey:@"account"];
//            [_saveDict setValue:[_areaBtn.titleLabel.text substringFromIndex:1] forKey:@"areaCode"];
//        }
//        else if ([validateInputValue validateEmail:_emailTextField.text])
//        {
//            [_saveDict setValue:_emailTextField.text forKey:@"account"];
//        }
        [_saveDict setValue:_nameTextField.text forKey:@"name"];
        [_saveDict setValue:_ceritificateTextField.text forKey:@"identity"];
        [_saveDict setValue:_sex forKey:@"gender"];
        postString = ADDGROUPCLIENT;
        if([self getTimestamp:_groupId timeKey:@"groupClient_timestamp"] != nil)
        {
            [_saveDict setValue:[self getTimestamp:_groupId timeKey:@"groupClient_timestamp"] forKey:@"timestamp"];
        }
        else
        {
            [_saveDict setValue:@"" forKey:@"timestamp"];
        }
        
    }
    else
    {
        [_saveDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
        [_saveDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
        [_saveDict setValue:_nameTextField.text forKey:@"name"];
        [_saveDict setValue:_sex forKey:@"gender"];
        [_saveDict setValue:_ceritificateTextField.text forKey:@"identify"];
        if ([_type intValue]==1) {
            if([validateInputValue isPureNumandCharacters:_phoneTextField.text]==YES)
            {
                [_saveDict setValue:_phoneTextField.text forKey:@"mobile"];
                [_saveDict setValue:[_areaBtn.titleLabel.text substringFromIndex:1] forKey:@"areaCode"];
            }
        }else{
            if ([validateInputValue validateEmail:_emailTextField.text]==YES)
            {
                [_saveDict setValue:_emailTextField.text forKey:@"email"];
            }
        }

//        if([validateInputValue isPureNumandCharacters:_phoneTextField.text]==YES)
//        {
//            [_saveDict setValue:_phoneTextField.text forKey:@"mobile"];
//            [_saveDict setValue:[_areaBtn.titleLabel.text substringFromIndex:1] forKey:@"areaCode"];
//        }
//        else if ([validateInputValue validateEmail:_emailTextField.text])
//        {
//            [_saveDict setValue:_emailTextField.text forKey:@"email"];
//        }
        postString = ADDGUEST;
        if([self getTimestamp:_communityId timeKey:@"customer_timestamp"] != nil)
        {
            [_saveDict setValue:[self getTimestamp:_communityId timeKey:@"customer_timestamp"] forKey:@"timestamp"];
        }
        else
        {
            [_saveDict setValue:@"" forKey:@"timestamp"];
        }
        [_saveDict setValue:_communityId forKey:@"communityId"];
    }
    
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [rnk initWithPath:POST(postString) params:_saveDict block:^(id downLoadData, id error)
     {
         if (_groupId) {
             if ([downLoadData objectForKey:@"cache"] ) {
                 if ([[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]integerValue] == 0)
                 {
                     [self updateTimestamp:_groupId timeKey:@"groupClient_timestamp" timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                 }
                 GuestModel * model = [[GuestModel alloc]init];
                 NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
                 data = [downLoadData objectForKey:@"data"];
                 model.email = [data objectForKey:@"email"];
                 model.firstChar = [data objectForKey:@"firstchar"];
                 model.sex = [data objectForKey:@"gender"];
                 model.headUrl = [data objectForKey:@"headurl"];
                 model.guestid = [data objectForKey:@"id"];
                 model.certificaties = [data objectForKey:@"identity"];
                 model.telePhone = [data objectForKey:@"mobile"];
                 model.guestName= [data objectForKey:@"name"];
                 model.isGroupManager = @"0";
                 if([validateInputValue isPureNumandCharacters:_phoneTextField.text]==YES)
                 {
                     model.areaCode = [_areaBtn.titleLabel.text substringFromIndex:1];
                 }
                 NSMutableArray * guestArray = [[NSMutableArray alloc]init];
                 [guestArray addObject:model];
                 
                 GroupGuestLogic *groupGuest = [[GroupGuestLogic alloc]init];
                 [groupGuest insertGroupGuestInfo:model groupName:_groupName groupStartTime:nil groupEndTime:nil groupId:_groupId];
                 GuestManagerViewController * gmvc = [[GuestManagerViewController alloc]init];
                 gmvc.communityid = _communityId;
                 gmvc.communityRole = _communityRole;
                 //            gmvc.allocateRoomPower = _allocateRoomPower;
                 gmvc.model = model;
                 gmvc.groupId = _groupId;
//                 editImgView.image = [UIImage imageNamed:@"ic_save"];
                 [self.navigationController pushViewController:gmvc animated:YES];
             }
         }
         else
         {
             if ([downLoadData objectForKey:@"cache"] != nil) {
                 if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]]]==YES)
                 {
                     if ([downLoadData objectForKey:@"data"] != nil)
                     {
                         NSDictionary * guestDict = [downLoadData objectForKey:@"data"];
                         GuestModel * model = [[GuestModel alloc]init];
                         model.guestid = [guestDict objectForKey:@"id"];
                         model.guestName = [guestDict objectForKey:@"name"];
                         model.sex = [guestDict objectForKey:@"gender"];
                         model.headUrl = [guestDict objectForKey:@"headurl"];
                         model.telePhone = [guestDict objectForKey:@"mobile"];
                         model.email = [guestDict objectForKey:@"email"];
                         model.certificaties = [guestDict objectForKey:@"identityId"];
                         if([validateInputValue isPureNumandCharacters:_phoneTextField.text]==YES)
                         {
                             model.areaCode = [_areaBtn.titleLabel.text substringFromIndex:1];
                         }
                         GuestManagerViewController * gmvc = [[GuestManagerViewController alloc]init];
                         gmvc.communityid = _communityId;
                         gmvc.communityRole = _communityRole;
                         //            gmvc.allocateRoomPower = _allocateRoomPower;
                         gmvc.model = model;
                         gmvc.groupId = _groupId;
                         GuestLogic *guestLogic = [[GuestLogic alloc]init];
                         [guestLogic insertStaffData:model withCommuntiyId:_communityId];
                         
//                         editImgView.image = [UIImage imageNamed:@"ic_save"];
                         [self.navigationController pushViewController:gmvc animated:YES];
                     }
                 }
                 else
                 {
                     [self updateTimestamp:_communityId timeKey:@"customer_timestamp" timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                     if ([downLoadData objectForKey:@"data"] != nil)
                     {
                         NSDictionary * guestDict = [downLoadData objectForKey:@"data"];
                         GuestModel * model = [[GuestModel alloc]init];
                         model.guestid = [guestDict objectForKey:@"id"];
                         model.guestName = [guestDict objectForKey:@"name"];
                         model.sex = [guestDict objectForKey:@"gender"];
                         model.headUrl = [guestDict objectForKey:@"headurl"];
                         model.telePhone = [guestDict objectForKey:@"mobile"];
                         model.email = [guestDict objectForKey:@"email"];
                         model.certificaties = [guestDict objectForKey:@"identityId"];
                         model.firstChar=[guestDict objectForKey:@"firstChar"];
                         model.firstChar = [self firstChar:model.guestName];
                         if([validateInputValue isPureNumandCharacters:_phoneTextField.text]==YES)
                         {
                             model.areaCode = [_areaBtn.titleLabel.text substringFromIndex:1];
                         }
                         GuestManagerViewController * gmvc = [[GuestManagerViewController alloc]init];
                         gmvc.communityid = _communityId;
                         gmvc.communityRole = _communityRole;
                         //            gmvc.allocateRoomPower = _allocateRoomPower;
                         gmvc.model = model;
                         gmvc.groupId = _groupId;
                         GuestLogic *guestLogic = [[GuestLogic alloc]init];
                         [guestLogic insertStaffData:model withCommuntiyId:_communityId];
                         
//                         editImgView.image = [UIImage imageNamed:@"ic_save"];
                         [self.navigationController pushViewController:gmvc animated:YES];
                     }
                 }
             }
             
         }
         if (error != nil) {
             [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
             NSLog(@"%@",error[@"info"]);
         }
         [self stopWaiting];
     }
     ];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
